package com.ly.cloudzuul.web;



import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.bean.Result;
import com.ly.damai.entity.util.JwtUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        // 127.0.0.1/user|cloud-user|.../login/login?...
        String path = request.getServletPath();
        System.out.println("path = " + path + " => " + path.matches("/[^/]+/login/login"));
        return path.matches("/[^/]+/login/login");
    }

    @Override
    public Object run() throws ZuulException {
        // 获取当前请求上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
//        String json = ctx.getResponseBody();
        String json = "";
        HttpServletResponse response = ctx.getResponse();
        ObjectMapper mapper = new ObjectMapper();
        try(InputStream inputStream = ctx.getResponseDataStream();
            InputStreamReader inputStreamReader =
                    new InputStreamReader(inputStream,"utf-8");) {
            char[] chars = new char[1024];
            int cnt = inputStreamReader.read(chars);
            json = new String(chars,0,cnt);
            Result result = mapper.readValue(json, Result.class);
            if (result.getCode() == 1) {
                // 构建jwt
                String jwt = JwtUtil.createJWT(30, (Map<String, Object>) result.getData());
                response.addHeader("Authorization", jwt);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 设置响应内容的类型和字符集
        response.setContentType("application/json;charset=utf-8");
        // 重新将 json 写入 响应对象
        ctx.setResponseBody(json);
        return null;
    }
}
